<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/2
 * Time: 18:33
 */

namespace Lib\Api;


class OrderApi extends UtilsApi {
    private static $modelName = "Order";

    public static function getList($where, $left, $page_num, $page_size, $field, $order = '', $group='') {
        $model = M();
        $list = $model->table('fs_order a')
            ->join($left)
            ->field($field)
            ->where($where)
            ->order($order)
            ->group($group)
            ->page($page_num, $page_size)
            ->select();

        return $list;
    }

    public static function getListAllByCondition($where, $left='', $field= "*", $order='', $group='') {
        $model = M();
        $list = $model->table('fs_order a')
            ->join($left)
            ->field($field)
            ->where($where)
            ->order($order)
            ->group($group)
            ->select();

        return $list;
    }

    public static function getSum($where, $field, $left='', $group='') {
        $model = M();
        $list = $model->table('fs_order a')
            ->join($left)
            ->where($where)
            ->group($group)
            ->sum($field);

        return $list;
    }

    /** 获取交易明细总数
     * @param $where
     * @param $left
     * @return mixed
     */
    public static function getTotal($where, $left='') {
        $model = M();
        $total = $model->table('fs_order a')
            ->join($left)
            ->where($where)
            ->count('a.id');
        return $total;
    }

    /** 获取详细信息
     * @param $where
     * @param $field
     * @return mixed
     */
    public static function getInfo($where, $field="*") {
        $model = M(OrderApi::$modelName);
        return $model->field($field)->where($where)->find();
    }

    public static function getListByCondition($where) {
        $model = M(OrderApi::$modelName);
        $list = $model->where($where)->select();
        return $list;
    }

    /** 修改订单
     * @param $data
     * @return bool
     */
    public static function save($data) {
        $state = parent::save(OrderApi::$modelName, $data);
        return $state;
    }

    /** 保存数据
     * @param $where
     * @param $data
     * @return bool
     */
    public static function saveByCondition($where, $data) {
        $model = M(OrderApi::$modelName);
        return $model->save($data)->where($where) ;
    }

    public static function getTotalGainMoneyByUserId($user_id) {
        $model = M();
        $total_gain_money = $model->table('fs_order a')
            ->where(array("a.user_id"=>$user_id))
            ->sum('a.gain_price');
        return $total_gain_money;

    }

    // 获取用户订单记录
    public static function toOrderList($user_id, $agent_level, $page_size, $page_num, $data_cycle) {
        $where = '';
        if ($data_cycle != "") {
            $search_date = explode('/', $data_cycle);
            $begin_date = $search_date[0];
            $end_date = $search_date[1];
            $where = ' and DATE_FORMAT(a.begin_time, "%Y-%m-%d") >= "'.$begin_date.'" and DATE_FORMAT(a.begin_time, "%Y-%m-%d") <= "'.$end_date.'"';
        }

        // 获取用户下级SQL
        $AGENTCONFIG = C('AGENTCONFIG');

        if ($AGENTCONFIG[$agent_level]['config'][5] == 0) {
            $lowersql = 'select GROUP_CONCAT(LOWERFIELD1) from (select LOWERFIELD2 from fs_user level_'.$agent_level.' LOWERLEFT group by level_'.$agent_level.'.id) t where t.id = '.$user_id;
            $lowerfield1 = array('IFNULL(t.id,0)');
            $lowerfield2 = array('level_'.$agent_level.'.id');
            $lowerleft = array();
            for ($i = ($agent_level + 1); $i < count($AGENTCONFIG); $i++) {
                array_push($lowerleft, "left join fs_user level_$i on level_$i.agent_id = level_" . ($i - 1) . ".id");
                array_push($lowerfield2, "GROUP_CONCAT(distinct level_$i.id) as level_$i");

                if (count($lowerfield1) > 0) {
                    array_push($lowerfield1, '","');
                }
                array_push($lowerfield1, "IFNULL(t.level_$i,0)");
            }
            $lowersql = str_replace("LOWERFIELD1", implode(',', $lowerfield1), $lowersql);
            $lowersql = str_replace("LOWERFIELD2", implode(',', $lowerfield2), $lowersql);
            $lowersql = str_replace("LOWERLEFT", implode(' ', $lowerleft), $lowersql);
        } else {
            $lowersql = $user_id;
        }

        $sql = 'select b.id user_id, b.mobile_phone,b.real_name,a.id,a.order_no,a.type,a.real_price,a.order_price,a.voucher_price,a.begin_time,a.gain_price,a.state, a.trade_time,c.game_name';
        $sql .= ' from fs_order a';
        $sql .= ' left join fs_user b on b.id = a.user_id';
        $sql .= ' left join fs_game_type c on c.id = a.play_type';
        $sql .= ' where find_in_set(a.user_id,('.$lowersql.'))'.$where.' order by a.begin_time desc limit '.(($page_num-1)*$page_size).','.$page_size;

        $model = new \Think\Model();
        $list = $model->query($sql);

        // var_dump($sql);

        $sql = 'select count(a.id) total from fs_order a left join fs_user b on b.id = a.user_id where find_in_set(a.user_id,('.$lowersql.')) '.$where;
        $model = new \Think\Model();
        $total = $model->query($sql);

        $rel =  pageHelper($page_size, $page_num, $list, $total[0]['total']);
        $data["data"] = $rel;
        return $data;
    }


    public static function toOrderNumStatistics($user_id, $begin_time, $end_time) {
        $where['DATE_FORMAT(a.begin_time, "%Y-%m-%d")'] = array(array('egt', $begin_time), array('elt',$end_time));
        $where['b.belong_user_id'] = $user_id;
        $model = M();
        $list = $model->table('fs_order a')
            ->field('count(a.id) as num,DATE_FORMAT(a.begin_time,"%Y-%m-%d") as datetime, c.game_name')
            ->join(' left join fs_user_belong b on b.user_id = a.user_id')
            ->join(' left join fs_game_type c on c.id = a.play_type')
            ->where($where)
            ->group('DATE_FORMAT(a.begin_time,"%Y-%m-%d"), a.play_type')
            ->select();

        return $list;

        /*$where = ' and DATE_FORMAT(a.begin_time, "%Y-%m-%d") >= "'.$begin_time.'" and DATE_FORMAT(a.begin_time, "%Y-%m-%d") <= "'.$end_time.'"';
        // 获取用户下级SQL
        $AGENTCONFIG = C('AGENTCONFIG');

        if ($AGENTCONFIG[$agent_level]['config'][5] == 0) {
            $lowersql = 'select GROUP_CONCAT(LOWERFIELD1) from (select LOWERFIELD2 from fs_user level_'.$agent_level.' LOWERLEFT group by level_'.$agent_level.'.id) t where t.id = '.$user_id;
            $lowerfield1 = array('IFNULL(t.id,0)');
            $lowerfield2 = array('level_'.$agent_level.'.id');
            $lowerleft = array();
            for ($i = ($agent_level + 1); $i < count($AGENTCONFIG); $i++) {
                array_push($lowerleft, "left join fs_user level_$i on level_$i.agent_id = level_" . ($i - 1) . ".id");
                array_push($lowerfield2, "GROUP_CONCAT(distinct level_$i.id) as level_$i");

                if (count($lowerfield1) > 0) {
                    array_push($lowerfield1, '","');
                }
                array_push($lowerfield1, "IFNULL(t.level_$i,0)");
            }
            $lowersql = str_replace("LOWERFIELD1", implode(',', $lowerfield1), $lowersql);
            $lowersql = str_replace("LOWERFIELD2", implode(',', $lowerfield2), $lowersql);
            $lowersql = str_replace("LOWERLEFT", implode(' ', $lowerleft), $lowersql);
        } else {
            $lowersql = $user_id;
        }

        $sql = 'select count(a.id) as num,DATE_FORMAT(a.begin_time,"%Y-%m-%d") as datetime, b.game_name';
        $sql .= ' from fs_order a';
        $sql .= ' left join fs_game_type b on b.id = a.play_type';
        $sql .= ' left join fs_user c on c.id = a.user_id';
        $sql .= ' where find_in_set(a.user_id,('.$lowersql.'))'.$where.' group by DATE_FORMAT(a.begin_time,"%Y-%m-%d"), a.play_type';

        $model = new \Think\Model();
        $list = $model->query($sql);

        return $list;*/
    }

    public static function getTotalOrderNum($user_id,$agent_level,$data_cycle) {
        // $order_where = '';
        if ($data_cycle != "all") {
            if ($data_cycle != "") {
                $search_date = explode('/', $data_cycle);
                $begin_date = $search_date[0];
                $end_date = $search_date[1];

                $order_where = ' and DATE_FORMAT(o.begin_time, "%Y-%m-%d") >= "'.$begin_date.'" and DATE_FORMAT(o.begin_time, "%Y-%m-%d") <= "'.$end_date.'"';
            } else {
                $order_where = ' and DATE_FORMAT(o.begin_time, "%Y-%m-%d") >= "'.date("Y-m-d").'" and DATE_FORMAT(o.begin_time, "%Y-%m-%d") <= "'.date("Y-m-d").'"';
            }
        }

        $AGENTCONFIG = C('AGENTCONFIG');

        // 获取用户下级SQL
        if ($AGENTCONFIG[$agent_level]['config'][5] == 0) {
            $lowersql = 'select GROUP_CONCAT(LOWERFIELD1) from (select LOWERFIELD2 from fs_user level_'.$agent_level.' LOWERLEFT group by level_'.$agent_level.'.id) t where t.id = '.$user_id;
            $lowerfield1 = array('IFNULL(t.id,0)');
            $lowerfield2 = array('level_'.$agent_level.'.id');
            $lowerleft = array();
            for ($i = ($agent_level + 1); $i < count($AGENTCONFIG); $i++) {
                array_push($lowerleft, "left join fs_user level_$i on level_$i.agent_id = level_" . ($i - 1) . ".id");
                array_push($lowerfield2, "GROUP_CONCAT(distinct level_$i.id) as level_$i");

                if (count($lowerfield1) > 0) {
                    array_push($lowerfield1, '","');
                }
                array_push($lowerfield1, "IFNULL(t.level_$i,0)");
            }
            $lowersql = str_replace("LOWERFIELD1", implode(',', $lowerfield1), $lowersql);
            $lowersql = str_replace("LOWERFIELD2", implode(',', $lowerfield2), $lowersql);
            $lowersql = str_replace("LOWERLEFT", implode(' ', $lowerleft), $lowersql);
        } else {
            $lowersql = $user_id;
        }

        // 订单总数SQL
        $sql = 'select ifnull(count(o.id), 0) total_order_num from fs_order o where find_in_set(o.user_id, (LOWERSQL)) '.$order_where;
        $sql = str_replace("LOWERSQL", $lowersql, $sql);

        $model = new \Think\Model();
        $list = $model->query($sql);
        return $list[0]['total_order_num'];
    }

    public static function getTotalOrderMoney($user_ids) {
        $real_total_price = 0;
        if (!empty($user_ids)) {
            $model = M(OrderApi::$modelName);
            $real_total_price = $model->where("user_id in($user_ids)")->sum("real_price");
        }

        return $real_total_price;
    }

    public static function getTotalOrdeGainMoney($user_ids) {
        $real_total_price = 0;
        if (!empty($user_ids)) {
            $model = M(OrderApi::$modelName);
            $real_total_price = $model->where("user_id in($user_ids)")->sum("gain_price");
        }

        return $real_total_price;
    }

}